package com.study.money.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.study.util.HttpUtils;
import com.study.money.common.FundTypeEnum;
import com.study.money.dao.entity.FundDO;
import com.study.money.dao.entity.NetWorthDO;
import org.apache.commons.lang3.StringUtils;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.math.BigDecimal;
import java.util.*;

/**
 * 天天基金工具
 *
 * @author wanghuilong
 * @version 1.0
 * @date 2022/2/14 8:42 上午
 */
public class TianTianJiJinUtil {


    private static Integer pageSize = 20;

    /**
     * 查询估值
     *
     * //天天基金接口当日净值增长不准/ **数据格式：{“ fundcode”：“ 161725”，//基金代码“ name”：“招商中证白酒指数（LOF）”“，//基金名称“ jzrq”：“ 2021-02-09”，//上一个结算日期“ dwjz”：“ 1.5439”，//上一个结算日期的单位净值“ gsz”：“ 1.6183”，//盘中实时净值投放“ gszzl”：“ 4.82”，//日投放“ gztime”：“ 2021-02-10 15:00” //最后更新日期} * /
     *
     * @return
     */
    public static BigDecimal getEstimateValue(String code,String queryDateStr) {
        long time = System.currentTimeMillis();
        String queryEstimateValueUrl = new StringBuilder("https://fundgz.1234567.com.cn/js/").append(code)
                .append(".js?rt=").append(time).toString();
        String s = HttpUtils.get(queryEstimateValueUrl);
        System.out.println(queryEstimateValueUrl);
        System.out.println(s);
        s = s.replace("jsonpgz(", "").replace(");", "");
        if(StringUtils.isEmpty(s)) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(s);
        String gsz = jsonObject.getString("gsz");
        String gztime = jsonObject.getString("gztime");
        if(gztime.indexOf(queryDateStr) > -1) {
            return new BigDecimal(gsz);
        }
        return null;
    }

    /**
     * 查询基金基本信息
     * @param code
     * @return
     */
    public static FundDO getFundInfo(String code) {
        long time = System.currentTimeMillis();
        String queryEstimateValueUrl = new StringBuilder("https://fundgz.1234567.com.cn/js/").append(code)
                .append(".js?rt=").append(time).toString();
        String s = HttpUtils.get(queryEstimateValueUrl);
        if(StringUtils.isEmpty(s)) {
            return null;
        }
        System.out.println(queryEstimateValueUrl);
        System.out.println(s);
        s = s.replace("jsonpgz(", "").replace(");", "");
        if(StringUtils.isEmpty(s)) {
            return null;
        }
        JSONObject jsonObject = JSONObject.parseObject(s);
        String name = jsonObject.getString("name");
        FundDO fundDO = new FundDO();
        fundDO.setCode(code);
        fundDO.setName(name);
        fundDO.setFundType(FundTypeEnum.FUND.getDesc());
        return fundDO;
    }

    /**
     * 查询基金基本信息
     * String queryEstimateValueUrl = new StringBuilder("https://fundgz.1234567.com.cn/js/").append(code)
     *                 .append(".js?rt=").append(time).toString();
     * jsonpgz({"fundcode":"002610","name":"鍗氭椂榛勯噾ETF鑱旀帴A","jzrq":"2022-03-08","dwjz":"1.4170","gsz":"1.4120","gszzl":"-0.36","gztime":"2022-03-08 20:11"});
     */


    /**
     * 查询基金历史净值数据
     * http://api.fund.eastmoney.com/f10/lsjz?callback=jQuery183011122541436750732_1646740053006&fundCode=002610&pageIndex=1&pageSize=20&startDate=2022-03-01&endDate=2022-03-08&_=1646740108329
     *
     * jQuery183011122541436750732_1646740053006({"Data":{"LSJZList":[{"FSRQ":"2022-03-08","DWJZ":"1.4170","LJJZ":"1.4170","SDATE":null,"ACTUALSYI":"","NAVTYPE":"1","JZZZL":"1.99","SGZT":"开放申购","SHZT":"开放赎回","FHFCZ":"","FHFCBZ":"","DTYPE":null,"FHSP":""},{"FSRQ":"2022-03-07","DWJZ":"1.3893","LJJZ":"1.3893","SDATE":null,"ACTUALSYI":"","NAVTYPE":"1","JZZZL":"1.85","SGZT":"开放申购","SHZT":"开放赎回","FHFCZ":"","FHFCBZ":"","DTYPE":null,"FHSP":""},{"FSRQ":"2022-03-04","DWJZ":"1.3640","LJJZ":"1.3640","SDATE":null,"ACTUALSYI":"","NAVTYPE":"1","JZZZL":"0.51","SGZT":"开放申购","SHZT":"开放赎回","FHFCZ":"","FHFCBZ":"","DTYPE":null,"FHSP":""},{"FSRQ":"2022-03-03","DWJZ":"1.3571","LJJZ":"1.3571","SDATE":null,"ACTUALSYI":"","NAVTYPE":"1","JZZZL":"-0.66","SGZT":"开放申购","SHZT":"开放赎回","FHFCZ":"","FHFCBZ":"","DTYPE":null,"FHSP":""},{"FSRQ":"2022-03-02","DWJZ":"1.3661","LJJZ":"1.3661","SDATE":null,"ACTUALSYI":"","NAVTYPE":"1","JZZZL":"1.69","SGZT":"开放申购","SHZT":"开放赎回","FHFCZ":"","FHFCBZ":"","DTYPE":null,"FHSP":""},{"FSRQ":"2022-03-01","DWJZ":"1.3434","LJJZ":"1.3434","SDATE":null,"ACTUALSYI":"","NAVTYPE":"1","JZZZL":"0.30","SGZT":"开放申购","SHZT":"开放赎回","FHFCZ":"","FHFCBZ":"","DTYPE":null,"FHSP":""}],"FundType":"002","SYType":null,"isNewType":false,"Feature":"030,031,050,051,070,411,412"},"ErrCode":0,"ErrMsg":null,"TotalCount":6,"Expansion":null,"PageSize":20,"PageIndex":1})
     */


    /**
     * 查询费率
     * @param code
     * @return
     */
    public static String getBuyInfoStr(String code) {
        String queryEstimateValueUrl = new StringBuilder("http://fundf10.eastmoney.com/jjfl_").append(code)
                .append(".html").toString();
        String html = HttpUtils.get(queryEstimateValueUrl);
        html = html.replace("<div class=\"boxitem w790\"><h4 class=\"t\"><label class=\"left\">赎回费率"
                ,"<div class=\"boxitem w790\" id=\"redemptionRate\"><h4 class=\"t\"><label class=\"left\">赎回费率");
        Document document = Jsoup.parse(html);
        Element redemptionRate = document.getElementById("redemptionRate");
        Elements tbody = redemptionRate.getElementsByTag("tbody");
        Element element = tbody.get(0);
        Elements tr = element.getElementsByTag("tr");
        for (int i = 0; i < tr.size(); i++) {
            Element element1 = tr.get(i);
            Elements td = element1.getElementsByTag("td");
            for (int j = 0; j < td.size() ; j++) {
                Element element2 = td.get(j);
                if("th".equals(element2.attr("class"))) {
                    continue;
                }
                System.out.println(element2.text());
            }
        }
        return null;
    }

    /**
     *
     * @param code
     * @param startDate
     * @return
     */
    public static List<NetWorthDO> getNetWorthList(String code, Date startDate, Date endDate) {
        Integer totalCount = getNetWorthCount(code, startDate,endDate);
        Integer pageNum = (totalCount/pageSize + (totalCount%pageSize==0?0:1));
        List<NetWorthDO> netWorthDOList = new ArrayList<>(5000);
        for (int i = 1; i <= pageNum ; i++) {
            List<NetWorthDO> netWorthDataList = getNetWorthDataList(code, startDate,endDate, i);
            if(null == netWorthDataList) {
                System.out.println("查询历史净值失败,code:"+code);
                return null;
            }
            netWorthDOList.addAll(netWorthDataList);
        }
        return netWorthDOList;
    }

    public static List<NetWorthDO> getNetWorthDataList(String code, Date startDate, Date endDate,Integer pageNum) {
        List<NetWorthDO> netWorthDOS = new ArrayList<>(20);
        String netWorthListStr = getNetWorthList(code, startDate,endDate, pageNum);
        if(StringUtils.isBlank(netWorthListStr)) {
            return null;
        }
        netWorthListStr = netWorthListStr.replace("jQuery183011122541436750732_1646740053006(","").replace(")","");
        JSONObject jsonObject = JSONObject.parseObject(netWorthListStr);
        JSONObject dataObj = jsonObject.getJSONObject("Data");
        if(null == dataObj) {
            return null;
        }
        JSONArray data = dataObj.getJSONArray("LSJZList");
        for (int i = 0; i < data.size(); i++) {
            JSONObject obj = data.getJSONObject(i);
            /**
             *                  "FSRQ":"2022-03-08", 净值日期
             *                 "DWJZ":"1.4170",  单位净值
             *                 "LJJZ":"1.4170",  累计净值
             *                 "SDATE":null,
             *                 "ACTUALSYI":"",
             *                 "NAVTYPE":"1",
             *                 "JZZZL":"1.99", 日增长率
             *                 "SGZT":"开放申购",
             *                 "SHZT":"开放赎回",
             *                 "FHFCZ":"",
             *                 "FHFCBZ":"",
             *                 "DTYPE":null,
             *                 "FHSP":""
             */
            System.out.println(obj.toJSONString());
            NetWorthDO netWorthDO = new NetWorthDO();
            String fsrq = obj.getString("FSRQ");
            String dwjz = obj.getString("DWJZ");
            if(StringUtils.isEmpty(dwjz)) {
                continue;
            }
            String jzzzl = obj.getString("JZZZL");
            String content = obj.getString("SGZT")+";"+obj.getString("SHZT");
            netWorthDO.setCode(code);
            netWorthDO.setFundType(FundTypeEnum.FUND.getDesc());
            netWorthDO.setNetWorth(new BigDecimal(dwjz));
            if(StringUtils.isBlank(jzzzl)) {
                jzzzl = "0";
            }
            netWorthDO.setGrowRate(new BigDecimal(jzzzl));
            netWorthDO.setTdate(DateUtil.parseDateStr(fsrq));
            netWorthDO.setComment(content);
            netWorthDOS.add(netWorthDO);
        }
        return netWorthDOS;
    }

    public static Integer getNetWorthCount(String code, Date startDate, Date endDate) {
        String netWorthListStr = getNetWorthList(code, startDate,endDate, 1);
        if(StringUtils.isBlank(netWorthListStr)) {
            return null;
        }
        netWorthListStr = netWorthListStr.replace("jQuery183011122541436750732_1646740053006(","").replace(")","");
        JSONObject jsonObject = JSONObject.parseObject(netWorthListStr);
        Integer totalCount = jsonObject.getInteger("TotalCount");
        if(null == totalCount){
            System.out.println("查询历史净值失败，code"+code+","+netWorthListStr);
            return null;
        }
        return totalCount;
    }

    public static String getNetWorthList(String code, Date startDate, Date endDate,Integer pageNum) {
        long time = System.currentTimeMillis();
        StringBuilder stringBuilder = new StringBuilder("http://api.fund.eastmoney.com/f10/lsjz?callback=jQuery183011122541436750732_1646740053006&fundCode=")
                .append(code).append("&pageIndex=").append(pageNum).append("&pageSize=20&startDate=");
        if(null != startDate) {
            stringBuilder.append(DateUtil.getDateFormatStr(startDate));
        }
        stringBuilder.append("&endDate=");
        if(null != endDate) {
            stringBuilder.append(DateUtil.getDateFormatStr(endDate));
        }
        String url = stringBuilder.append("&_=").append(time).toString();
        Map<String,String> header = new HashMap<>();
        header.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.109 Safari/537.36");
        header.put("Referer","http://fundf10.eastmoney.com/");
        return HttpUtils.get(url, null, header);
    }





    public static void main(String[] args) {
//        String s = HttpUtils.get("http://fund.eastmoney.com/js/fundcode_search.js");
//        s = s.replace("var r = ","").replace(";","");
//        FileUtil.writeToFile(s,"/Users/wanghuilong/IdeaProjects/lazy/springUtil/src/test/resources/file/codes.txt");
//        StringBuilder stringBuilder = new StringBuilder();
//        JSONArray jsonArray = JSONArray.parseArray(s);
//        for (int i = 0; i < jsonArray.size(); i++) {
//            JSONArray subArr = jsonArray.getJSONArray(i);
//            System.out.println(subArr.getString(0));
//        }
//        for (int i = 0; i < 20; i++) {
//            long time = System.currentTimeMillis();
//            String url = new StringBuilder("http://api.fund.eastmoney.com/f10/lsjz?callback=jQuery183011122541436750732_1646740053006&fundCode=002610&pageIndex=")
//                    .append(i).append("&pageSize=20&startDate=&endDate=&_=").append(time).toString();
//            Map<String,String> header = new HashMap<>();
//            header.put("User-Agent","Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/98.0.4758.109 Safari/537.36");
//            header.put("Referer","http://fundf10.eastmoney.com/");
//            String s = HttpUtils.get(url, null, header);
//            System.out.println("第"+i+"页：");
//            System.out.println(s);
//        }

        String str = "<if test=\"freeShipping != null\">\n" +
                "                free_shipping = #{freeShipping},\n" +
                "            </if>\n" +
                "            <if test=\"freeShippingQuantity != null\">\n" +
                "                free_shipping_quantity = #{freeShippingQuantity},\n" +
                "            </if>\n" +
                "            <if test=\"availableAssetTypes != null and availableAssetTypes != ''\">\n" +
                "                available_asset_types = #{availableAssetTypes},\n" +
                "            </if>\n" +
                "            <if test=\"useAssetsOnlyFlag != null\">\n" +
                "                use_assets_only_flag = #{useAssetsOnlyFlag},\n" +
                "            </if>\n" +
                "            <if test=\"refundFlag != null\">\n" +
                "                refund_flag = #{refundFlag},\n" +
                "            </if>\n" +
                "            <if test=\"returnFlag != null\">\n" +
                "                return_flag = #{returnFlag},\n" +
                "            </if>\n" +
                "            <if test=\"deliveryWay != null and deliveryWay != ''\">\n" +
                "                delivery_way = #{deliveryWay},\n" +
                "            </if>\n" +
                "            <if test=\"itemRemark != null\">\n" +
                "                item_remark = #{itemRemark},\n" +
                "            </if>\n" +
                "            <if test=\"operationUserId != null\">\n" +
                "                operation_user_id = #{operationUserId},\n" +
                "            </if>";

        String[] splitStrArr = str.split("</if>");
        for (String s:splitStrArr) {
            s = s.trim();
            s = s.replaceAll(",\n",",");
//            System.out.println(s);
            String[] subSplitStrArr = s.trim().split("\n");
            String test = subSplitStrArr[0].trim().replace("<if test=\"","").replace("\">","");
            String[] split2 = subSplitStrArr[1].trim().split("=");
            String tableColName = split2[0].trim();
            String objField = split2[1].trim().replace("#{","").replace("}","").replace(",","");
            test = test.replace(objField,"item."+objField);
            String updateValue = split2[1].trim().replace("#{","#{item.").replace(",","");

//            System.out.println(test);
//            System.out.println(tableColName);
//            System.out.println(updateValue);
            String template = "<trim prefix=\"${tableColName}=case\" suffix=\"end,\">\n" +
                    "                    <foreach collection=\"updateInfoList\" item=\"item\">\n" +
                    "                        <if test=\"${test}\">\n" +
                    "                            when item_code = #{item.itemCode} then ${updateValue}\n" +
                    "                        </if>\n" +
                    "                    </foreach>\n" +
                    "                </trim>";
            String resultStr = template.replace("${tableColName}",tableColName).replace("${objField}",objField)
                    .replace("${test}",test).replace("${updateValue}",updateValue);
            System.out.println(resultStr);
        }

    }

}
